//
//  AppDelegate.m
//  WisdomStar
//
//  Created by zhangliwen on 2018/10/13.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "AppDelegate.h"

#import "WSModuleManager.h"
#import <AlipaySDK/AlipaySDK.h>
@interface AppDelegate ()
@property(nonatomic, strong) Hen_AppDelegateManager *appDelegateManager;
@end

@implementation AppDelegate
// 设置window
- (void)setUpWindow {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [WSModuleManager getRootController];
    [self.window makeKeyAndVisible];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [self setUpWindow];
    
    [[Hen_AppDelegateManager shareAppDelegateManager] relatedInitialization];
    
    //初始化高得地图
    [DATAMODEL.aMapUtil initAMap];
    
    /// 配置服务器
    [self setupServer];
    
    /// 注册通知
    [self addNotifations];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark -- 跳转回来

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
//    return [self.appDelegateManager application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000)) {
                
                // 发通知带出支付成功结果
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnSucceedPayNotification" object:resultDic];
            } else {
                
                // 发通知带出支付失败结果
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnFailedPayNotification" object:resultDic];
            }
        }];
    }
    
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"支付宝网页版result = %@",resultDic);
            if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000)) {
                
                // 发通知带出支付成功结果
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnSucceedPayNotification" object:resultDic];
            } else {
                
                // 发通知带出支付失败结果
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAliReturnFailedPayNotification" object:resultDic];
            }
        }];
    }
    return YES;

}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [self.appDelegateManager application:application handleOpenURL:url];
}

#pragma mark -- push

///注册DeviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [self.appDelegateManager application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    
    NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                 stringByReplacingOccurrencesOfString: @">" withString: @""]
                                stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSLog(@"=====DeviceToken:%@", deviceTokenStr);
    DATAMODEL.deviceToken = deviceTokenStr;
}

///接收到通知 后台执行多任务
- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    [self.appDelegateManager application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

///错误处理
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    [self.appDelegateManager application:application didFailToRegisterForRemoteNotificationsWithError:error];
}



/**
 配置网络服务
 */
- (void)setupServer {
    [IOAApiManager configNetwork];
    [IOAApiManager startNetworkMonitoring];
}


#pragma mark - 注册通知

- (void)addNotifations {
    [kNotificationCenter addObserver:self selector:@selector(tokenDidExpired) name:WSTokenExpiredNotificationKey object:nil];
}


/**
 登录过期
 */
- (void)tokenDidExpired {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"登录过期" message:nil preferredStyle:UIAlertControllerStyleAlert];
        // sure
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [WSModuleManager showLoginMoudle];
        }];
        [alertController addAction:sureAction];
        [KAppWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    });
}

@end
